package com.xmlt.core.template.tags;

import java.util.ArrayList;
import java.util.List;

import ognl.OgnlException;

import com.xmlt.core.template.expression.ExpressionFactory;
import com.xmlt.core.template.expression.InstancePropertyAccessor;
import com.xmlt.core.template.instance.AbstractInstance;

public class OutputTag extends TemplateSectionElement {

	public OutputTag() {
	}

	public String toString() {
		return "output: (" + getParameterValue("expression") + ")";
	}

	public String getExpression() {
		return getParameterValue("expression");
	}

	@Override
	public List<TemplateSectionElement> generateTags(AbstractInstance instance) {
		ArrayList<TemplateSectionElement> tags = new ArrayList<TemplateSectionElement>();
		Object o = null;
		try {
			InstancePropertyAccessor.resolve = false;
			o = ExpressionFactory.getExpression(getParameterValue("expression")).evaluate(instance, false);
		} catch (Exception e) {
			tags.add(new TextTag(e.getMessage()));
			return tags;
		} finally {
			InstancePropertyAccessor.resolve = true;
		}
		if (o instanceof AbstractInstance) {
			AbstractInstance paramInstance = (AbstractInstance) o;
			OutputTag newTag = new OutputTag();
			newTag.setParameter("expression", paramInstance.getPath());
			tags.add(newTag);
		} else {
			tags.add(new TextTag(String.valueOf(o)));
		}
		
		return tags;
	}
	
	public Object getValue(AbstractInstance instance) throws OgnlException {
		Object o = null;
		try {
			InstancePropertyAccessor.resolve = false;
			o = ExpressionFactory.getExpression(getParameterValue("expression")).evaluate(instance, false);
		} finally {
			InstancePropertyAccessor.resolve = true;
		}
		return o;
	}
}
